<#import "/macro.ftl" as m>
<@m.page_header title='APP启动画面' />
<div id="page-content-wrapper">
    <div id="page-title">
        <h3>APP启动画面</h3>
    </div>
    <div id="page-content">
    	<form id="form" action="/splashscreenschedules/add" method="post">
    		<div class="row">
    			<div class="col-md-4">
    				<div class="form-row">
		    			<div class="form-label col-md-4">
		    				<label id="device">设备：</label>
		    			</div>
		    			<div class="form-input col-md-6">
		    				<select id="device" name="device" onchange="onDeviceChanged( this );">
		    					<option value="iOS" <#if schedule.device == 'iOS'>selected</#if> >iOS</option>
		    					<option value="Android" <#if schedule.device == 'Android'>selected</#if> >Android</option>
		    				</select>
		    			</div>
		    		</div>
    			</div>
    			<div class="col-md-4">
    				<div class="form-row">
		    			<div class="form-label col-md-4">
		    				<label id="startTime">开始时间：</label>
		    			</div>
		    			<div class="form-input col-md-6">
		    				<input id="startTime" name="startTime" value="<#if schedule.startTime??>${schedule.startTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" data-required="true" onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})" type="text">
		    			</div>
		    		</div>
    			</div>
    			<div class="col-md-4">
    				<div class="form-row">
		    			<div class="form-label col-md-4">
		    				<label id="endTime">结束时间：</label>
		    			</div>
		    			<div class="form-input col-md-6">
		    				<input id="endTime" name="endTime" value="<#if schedule.endTime??>${schedule.endTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" data-required="true" onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})" type="text">
		    			</div>
		    		</div>
    			</div>
    		</div>
    		<div class="row">
    			<div class="col-md-4">
    				<div class="form-row">
		    			<div class="form-label col-md-4">
		    				<label id="priority">显示优先级：</label>
		    			</div>
		    			<div class="form-input col-md-6">
		    				<input id="priority" name="priority" value="${schedule.priority}" data-required="true" type="text">
		    			</div>
		    		</div>
    			</div>
    			<div class="col-md-8">
    				<div class="form-row">
		    			<div class="form-label col-md-2">
		    				<label id="description">描述：</label>
		    			</div>
		    			<div class="form-input col-md-9">
		    				<input id="description" name="description" value="${schedule.description}" data-required="true" type="text">
		    			</div>
		    		</div>
    			</div>
    		</div>
	    	<div id="images-content" class="row">
	    		<#assign i = 0 >
	    		<#list schedule.images as image>
	    		<div id="image-content-${i}" class="col-md-3 text-center">
	    			<div>
		    			<label class="font-size-15">分辨率 ：${image.width}x${image.height}</label>
		    		</div>
	    			<img id="image-${i}" width="220" height="300" src="<#if image.url?? && image.url?length gt 0 >${image.url}<#else>/assets/images/splashscreen.png</#if>" onclick="triggerFileupload('image-input-${i}');"></img>
	    			<input id="image-input-${i}" type="file" name="images" multiple="" class="hide">
    				<input id="images[${i}].width" name="images[${i}].width" value="${image.width}" type="hidden">
    				<input id="images[${i}].height" name="images[${i}].height" value="${image.height}" type="hidden">
    				<input id="images[${i}].dpi" name="images[${i}].dpi" value="${image.dpi}" type="hidden">
    				<input id="images[${i}].fileName" name="images[${i}].fileName" value="${image.fileName}" type="hidden">
    				<input id="images[${i}].url" name="images[${i}].url" value="${image.url}" type="hidden">
    				<input id="images[${i}].startTime" name="images[${i}].startTime" value="<#if image.startTime??>${image.startTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
    				<input id="images[${i}].endTime" name="images[${i}].endTime" value="<#if image.endTime??>${image.endTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
	    			<#assign i = i + 1 >
	    		</div>
	    		</#list>
	    	</div>
	    	<div class="row">
	    		<div class="col-md-10">
	    			<a href="javascript:;" class="btn large primary-bg radius-all-4 float-right" onclick="submit('form');">
                    	<span class="button-content">保存</span>
                    </a>
	    		</div>
	    	</div>
    	</form>
    </div>
</div>

<div id="ios-template" class="hide">
	<#assign i = 0 >
	<#list iOSImages as image>
	<div id="image-content-${i}" class="col-md-3 text-center">
		<div>
			<label class="font-size-15">分辨率 ：${image.width}x${image.height}</label>
		</div>
		<img id="image-${i}" width="220" height="300" src="<#if image.url?? && image.url?length gt 0 >${image.url}<#else>/assets/images/splashscreen.png</#if>" onclick="triggerFileupload('image-input-${i}');"></img>
		<input id="image-input-${i}" type="file" name="images" multiple="" class="hide">
		<input id="images[${i}].width" name="images[${i}].width" value="${image.width}" type="hidden">
		<input id="images[${i}].height" name="images[${i}].height" value="${image.height}" type="hidden">
		<input id="images[${i}].dpi" name="images[${i}].dpi" value="${image.dpi}" type="hidden">
		<input id="images[${i}].fileName" name="images[${i}].fileName" value="${image.fileName}" type="hidden">
		<input id="images[${i}].url" name="images[${i}].url" value="${image.url}" type="hidden">
		<input id="images[${i}].startTime" name="images[${i}].startTime" value="<#if image.startTime??>${image.startTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
		<input id="images[${i}].endTime" name="images[${i}].endTime" value="<#if image.endTime??>${image.endTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
		<#assign i = i + 1 >
	</div>
	</#list>
</div>

<div id="android-template" class="hide">
	<#assign i = 0 >
	<#list androidImages as image>
	<div id="image-content-${i}" class="col-md-3 text-center">
		<div>
			<label class="font-size-15">分辨率 ：${image.width}x${image.height}</label>
		</div>
		<img id="image-${i}" width="220" height="300" src="<#if image.url?? && image.url?length gt 0 >${image.url}<#else>/assets/images/splashscreen.png</#if>" onclick="triggerFileupload('image-input-${i}');"></img>
		<input id="image-input-${i}" type="file" name="images" multiple="" class="hide">
		<input id="images[${i}].width" name="images[${i}].width" value="${image.width}" type="hidden">
		<input id="images[${i}].height" name="images[${i}].height" value="${image.height}" type="hidden">
		<input id="images[${i}].dpi" name="images[${i}].dpi" value="${image.dpi}" type="hidden">
		<input id="images[${i}].fileName" name="images[${i}].fileName" value="${image.fileName}" type="hidden">
		<input id="images[${i}].url" name="images[${i}].url" value="${image.url}" type="hidden">
		<input id="images[${i}].startTime" name="images[${i}].startTime" value="<#if image.startTime??>${image.startTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
		<input id="images[${i}].endTime" name="images[${i}].endTime" value="<#if image.endTime??>${image.endTime?string('yyyy-MM-dd HH:mm:ss')}</#if>" type="hidden">
		<#assign i = i + 1 >
	</div>
	</#list>
</div>

<script type="text/javascript" src="/assets/js/md5.js"></script>
<script type="text/javascript" src="/assets/js/uuid.core.js"></script>
<script src="/assets/multiupload/jquery.iframe-transport.js"></script>
<script src="/assets/multiupload/jquery.fileupload.js"></script>

<script>

<#if error??>
	$.jGrowl("${error?html}", {sticky:!1,position:"top-right",theme:"bg-red"});
</#if>

//上传图片到又拍云
function uploadToUpyun(file, success) {

    $.get("/upyun/bucketapi", function (data) {

        var config = {
            api: 'http://v0.api.upyun.com/',
            bucket: data.bucket,
            // 空间的表单 API
            form_api: data.formId
        };
        
        if (!file) {
            console.log('no file is selected');
            return;
        }
        
        var date = new Date();
        var dir = "upload/images/splashscreens/" + date.getFullYear() + "/" + (date.getMonth() + 1) + "/";
        var fileName = UUID.generate() + '.png';
        
        // 计算 policy 和 signature 所需的参数
        // 详情见： http://docs.upyun.com/api/form_api/#表单API接口简介
        var options = {
            bucket: config.bucket,
            expiration: Math.floor(new Date().getTime() / 1000) + 86400,
            'save-key': dir + fileName
        };

        var policy = window.btoa(JSON.stringify(options));
        var signature = CryptoJS.MD5(policy + '&' + config.form_api);

        var dataform = new FormData();
        dataform.append('policy', policy);
        dataform.append('signature', signature);
        dataform.append('file', file);

        var request = new XMLHttpRequest();
        request.open('POST', config.api + options.bucket);

        request.onload = function (e) {
        	
            var jsonResponse = JSON.parse(request.response);
            if (jsonResponse.code == "200") {
                var uploadUrl = data.returnUrl + '/'+ dir + fileName;
                if(success){
                	success(uploadUrl);
                }
				
                $.jGrowl("上传又拍云成功", {sticky: !1, position: "top-right", theme: "bg-green"});
            } else {
                $.jGrowl("上传又拍云失败，错误代码" + jsonResponse.code, {sticky: !1, position: "top-right", theme: "bg-green"});
            }
        };

        request.send(dataform);
    });
}

// 提交表单
function submit(formId){
	var valid = $('#' + formId).parsley( 'validate' );
	if(!valid){
		return;
	}
	
	$('#' + formId).submit();
}

// 触发上传图片
function triggerFileupload( imageInputId ) {

	$( '#' + imageInputId ).fileupload({
        dataType: 'json',
        add: function (e, data) {
            uploadToUpyun(data.files[0], function(url){
            	var imageInputId = data.fileInput.attr('id');
            	var imageContentId = imageInputId.replace(/image-input/, 'image-content');
            	var imageContent = $('#' + imageContentId);
            	imageContent.find('img').attr('src', url);
            	imageContent.find('input[name$="url"]').val(url);
            });
        }
    });
    
    $( '#' + imageInputId ).trigger('click');
}

// 设备改变
function onDeviceChanged( sender ) {
	var device = $(sender);
	if (device.val() == 'iOS') {
		$( '#images-content' ).html($( '#ios-template' ).html());
	} else {
		$( '#images-content' ).html($( '#android-template' ).html());
	}
}
    
</script>